/**
 * 
 */
package com.cchr.acms.util;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Zeng,Fanxin
 *
 */
public class DataUtil {
	
	public static List<ChangeResult> compareObjectByFields(Object oldObject, Object newObject, List<String> needComparedFields) throws SecurityException, IllegalArgumentException, IllegalAccessException{
		List<ChangeResult> result = new ArrayList<ChangeResult>();
		if(oldObject == null && newObject == null){
			return result;
		}
		if(needComparedFields == null || needComparedFields.size() == 0){
			needComparedFields = new ArrayList<String>();
			Field[] fs = oldObject.getClass().getDeclaredFields();
			for(Field f:fs){
				needComparedFields.add(f.getName());
			}
		}
		
		if(oldObject != null && newObject == null){
			for(String fn:needComparedFields){
				Field f;
				try {
					f = oldObject.getClass().getDeclaredField(fn);
					f.setAccessible(true);
					Object v = f.get(oldObject);
					ChangeResult cr = new ChangeResult();
					cr.setKey(fn);
					cr.setOldValue(null);
					cr.setNewValue(v);
					result.add(cr);
				} catch (NoSuchFieldException e) {
					continue;
				}
			}
			return result;
		}
		
		if(oldObject == null && newObject != null){
			for(String fn:needComparedFields){
				try {
					Field f = newObject.getClass().getDeclaredField(fn);
					f.setAccessible(true);
					Object v = f.get(newObject);
					ChangeResult cr = new ChangeResult();
					cr.setKey(fn);
					cr.setOldValue(v);
					cr.setNewValue(null);
					result.add(cr);
				} catch (NoSuchFieldException e) {
					continue;
				}
			}
			return result;
		}
		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
		for(String fn:needComparedFields){
			try {
				Field f1 = oldObject.getClass().getDeclaredField(fn);
				Field f2 = newObject.getClass().getDeclaredField(fn);
				f1.setAccessible(true);
				f2.setAccessible(true);
				Object v1 = f1.get(oldObject);
				Object v2 = f1.get(newObject);
				if(v1 == null && v2 == null){
					continue;
				}
				ChangeResult cr = new ChangeResult();
				cr.setKey(fn);
				if(f1.getType() == Date.class)
				{
					if(v1 == null)
					{
						cr.setOldValue(v1);
					}
					else
					{
						cr.setOldValue(simpleDateFormat.format(v1));
					}
					if(v2 == null)
					{
						cr.setNewValue(v2);
					}
					else
					{
						cr.setNewValue(simpleDateFormat.format(v2));
					}
				}
				else
				{
					cr.setOldValue(v1);
					cr.setNewValue(v2);
				}
				if((v1 != null && v2 != null && !v1.equals(v2)) || (v1 != null && v2 == null) || (v1 == null && v2 != null)){
					result.add(cr);
				}
			} catch (NoSuchFieldException e) {
				continue;
			}
		}
		return result;
	}
}
